from datetime import datetime

from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import declarative_base
from init.mysql import engine

Base = declarative_base()


class Role(Base):
    __tablename__ = 'roles'
    id = Column(Integer, primary_key=True)
    orderNo = Column(Integer)
    roleName = Column(String(50))
    roleValue = Column(String(50))
    createTime = Column(DateTime)
    remark = Column(String(100))

    def __init__(self, order_no, role_name, role_value, remark):
        self.orderNo = order_no,
        self.roleName = role_name
        self.roleValue = role_value
        self.remark = remark
        self.createTime = datetime.now()

    def serialize(self) -> dict:
        return {
            "id": self.id,
            "orderNo": self.orderNo,
            "roleName": self.roleName,
            "roleValue": self.roleValue,
            "createTime": self.createTime.strftime("%Y-%m-%d %H:%M:%S"),
            "remark": self.remark,
        }

    def create(self, session):
        session.add(self)

    @staticmethod
    def update(session, id_, role):
        m = session.query(Role).filter_by(id=id_).first()
        m.roleName = role.roleName
        m.roleValue = role.roleValue
        m.orderNo = role.orderNo

    @staticmethod
    def delete(session, id_):
        session.query(Role).filter_by(id=id_).delete()

    @staticmethod
    def get_by_id(session, id_):
        return session.query(Role).filter_by(id=id_).first()


class UserRole(Base):
    __tablename__ = 'user_role'
    __table_args__ = {'comment': '角色权限表'}
    rid = Column(Integer, ForeignKey('roles.id'), primary_key=True, nullable=False)
    mid = Column(Integer, ForeignKey('users.user_id'), primary_key=True, nullable=False, index=True)

    def __init__(self,rid,mid):
        self.rid = rid
        self.mid = mid

    @staticmethod
    def get_roles(session, uid):
        urs = session.query(UserRole).filter_by(mid=uid).all()
        roles = []
        for ur in urs:
            role = Role.get_by_id(session, ur.rid)
            roles.append(role)
        return roles


Base.metadata.create_all(engine)
